<script>
	import * as THREE from 'three';
	import Globe from 'globe.gl';
	import { onMount } from 'svelte';
	let width, height;
	let world;
	const N = 300;
	const gData = [...Array(N).keys()].map(() => ({
		lat: (Math.random() - 0.5) * 180,
		lng: (Math.random() - 0.5) * 360,
		alt: Math.random() * 0.8 + 0.1,
		radius: Math.random() * 5,
		color: ['red', 'white', 'blue', 'green'][Math.round(Math.random() * 3)]
	}));
	onMount(() => {
		world = Globe()(document.getElementById('globeViz'));
		width = innerWidth;
		world

			.width(width - width / 5 - 50)
			.height(height)
			.backgroundColor('rgba(0,0,0,0)')
			.globeImageUrl('//unpkg.com/three-globe/example/img/earth-blue-marble.jpg')
			.bumpImageUrl('//unpkg.com/three-globe/example/img/earth-topology.png')
			.pointOfView({ altitude: 3.5 })
			.customLayerData(gData)
			.customThreeObject(
				(d) =>
					new THREE.Mesh(
						new THREE.SphereBufferGeometry(d.radius),
						new THREE.MeshLambertMaterial({ color: d.color })
					)
			)
			.customThreeObjectUpdate((obj, d) => {
				Object.assign(obj.position, world.getCoords(d.lat, d.lng, d.alt));
			});

		(function moveSpheres() {
			gData.forEach((d) => (d.lat += 0.2));
			world.customLayerData(world.customLayerData());
			requestAnimationFrame(moveSpheres);
		})();
		// custom globe material
		const globeMaterial = world.globeMaterial();
		globeMaterial.bumpScale = 10;
		new THREE.TextureLoader().load(
			'//unpkg.com/three-globe/example/img/earth-water.png',
			(texture) => {
				globeMaterial.specularMap = texture;
				globeMaterial.specular = new THREE.Color('grey');
				globeMaterial.shininess = 15;
			}
		);
	});
</script>

<div id="globeViz" />
